package com.yonyou.cyxdms.sysAuth.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.SystemParamDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.SystemParamPO;
import com.yonyou.cyxdms.sysAuth.service.entity.UserPO;
import com.yonyou.cyxdms.sysAuth.service.feign.OpsTaskService;
import com.yonyou.cyxdms.sysAuth.service.mapper.CompanyMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.SystemParamMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.UserMapper;
import com.yonyou.cyxdms.sysAuth.service.service.Login.UserLoginServiceImpl;
import com.yonyou.cyxdms.sysAuth.service.service.SystemParamService;
import com.yonyou.cyxdms.sysAuth.service.vo.rule.AdviceVO;
import com.yonyou.cyxdms.sysmanage.client.vo.advice.AdviceRuleVO;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author ：quankk
 * @date ：2019/7/9 15:46
 * @description：
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SystemParamServiceImpl implements SystemParamService {

    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(UserLoginServiceImpl.class);

    @Autowired
    public SystemParamMapper systemParamMapper;

    @Autowired
    public OpsTaskService opsTaskService;

    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * @author ：quankk
     * @date ：2019/7/9 15:49
     * @description：
     */
    @Override
    public Map<String, Object> getCommonData() {
        Map<String, Object> commonDataMap = new HashMap<>();
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        commonDataMap.put("userInfo", loginInfoDto);
        LambdaQueryWrapper<SystemParamPO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(SystemParamPO::getAppId, "RL").eq(SystemParamPO::getCompanyId, "1");
        List<SystemParamPO> list = systemParamMapper.selectList(queryWrapper);
        Map<String, Map<String, Object>> systemParamMap = new HashMap<>();
        list.forEach(row -> {
            String paramType = row.getParamType().toString();
            if (!systemParamMap.containsKey(paramType)) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put(row.getParamCode(), row.getParamValue());
                systemParamMap.put(paramType, paramMap);
            } else {
                Map<String, Object> paramMap = systemParamMap.get(paramType);
                paramMap.put(row.getParamCode(), row.getParamValue());
            }
        });
        commonDataMap.put("systemParam", systemParamMap);
        return commonDataMap;
    }

    @Override
    public List<SystemParamPO> querySystemParaList() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        LambdaQueryWrapper<SystemParamPO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(SystemParamPO::getAppId, loginInfoDto.getAppId()).eq(SystemParamPO::getCompanyId, loginInfoDto.getCompanyId());
        List<SystemParamPO> list = systemParamMapper.selectList(queryWrapper);

        return list;
    }

    @Override
    public void updateSystemPara(List<SystemParamDTO> systemParamDTO) {
        for (int i = 0; i < systemParamDTO.size(); i++) {
            SystemParamPO po = systemParamMapper.selectById(systemParamDTO.get(i).getParamId());
            po.setParamValue(systemParamDTO.get(i).getParamValue());

            systemParamMapper.updateById(po);
        }
    }

    /**
     * 获取指定经销商配置的策略信息
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/8/15
     */
    @Override
    public String getRatioByownerCode(Long companyId) {
        LambdaQueryWrapper<SystemParamPO> query = new QueryWrapper<SystemParamPO>().lambda();
        query.eq(SystemParamPO::getCompanyId, companyId);
        query.eq(SystemParamPO::getParamType, 7030);
        SystemParamPO param = systemParamMapper.selectOne(query);
        return null == param ? null : param.getParamCode();
    }

    /**
     * 通知规则设定
     *
     * @param:
     * @return:
     * @auther: 李贺
     * @since: 2019/9/16
     */
    @Override
    @Transactional
    public void setAdviceRules(List<AdviceVO> advicevos) {

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        for (AdviceVO adviceVO : advicevos) {
            LambdaQueryWrapper<SystemParamPO> query = new QueryWrapper<SystemParamPO>().lambda();
            query.eq(SystemParamPO::getParamCode, adviceVO.getParamCode());
            query.eq(SystemParamPO::getCompanyId, loginInfoDto.getCompanyId());
            query.eq(SystemParamPO::getParamType, 1001);

            setSchedule(query, adviceVO.getParamCode(), adviceVO.getParamName(), adviceVO.getParamValue());
        }


    }

    @Transactional
    public void setSchedule(LambdaQueryWrapper<SystemParamPO> query, String paramCode, String paramName, String time) {

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        SystemParamPO systemparampo = null;
        try {
            //查询 任务定时提醒时间
            systemparampo = systemParamMapper.selectOne(query);

            //更新 任务定时提醒时间
            systemparampo.setParamValue(time);
            systemParamMapper.updateById(systemparampo);

        } catch (NullPointerException e) {
            //新增 任务定时提醒时间
            systemparampo = new SystemParamPO();
            systemparampo.setAppId(loginInfoDto.getAppId());
            systemparampo.setCompanyId(loginInfoDto.getCompanyId());
            systemparampo.setParamType(1001);
            systemparampo.setParamCode(paramCode);
            systemparampo.setParamName(paramName);
            systemparampo.setStatus(ManageDictCodeConstants.STATUS_IS_YES);
            systemparampo.setParamValue(time);
            systemparampo.setIsDeleted(0);
            systemparampo.setRecordVersion(0);
            systemParamMapper.insert(systemparampo);

        }

    }

    /**
     * 通知规则查询
     *
     * @return:
     * @auther: 李贺
     * @since: 2019/9/16
     */
    @Override
    public List<AdviceVO> getAdviceRule(List<String> paramCodes) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        Long companyId = loginInfoDto.getCompanyId();
        Integer paramType = 1001;
        List<AdviceVO> advicevos = systemParamMapper.selectListByCode(paramCodes, companyId, paramType);

        return advicevos;
    }

    /**
     * 通知规则查询，根据paramCode
     *
     * @auther: 李贺
     * @since: 2019/9/18
     */
    @Override
    public List<AdviceRuleVO> getAdviceRules(String paramCode) {
        return systemParamMapper.getAdviceRules(paramCode);
    }

    /**
     * 根据code查询配置的value
     *
     * @param paramCode 配置code
     * @param appId     租户ID
     * @return
     * @auth houkh
     * @since 2019/11/26
     */
    @Override
    public String getParamValueByCode(String paramCode, String appId) {
        return systemParamMapper.getParamValueByCode(paramCode, appId);
    }

    //判断是否需要密码更新
    @Override
    public Integer needUpdate() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        List<Map<String,String>> systemparampos = systemParamMapper.findFactoryParam(companyMapper.findFactoryIdByAppId(loginInfoDto.getAppId()),"updateTime");
        if (CollectionUtils.isEmpty(systemparampos)) {
            return 10041002;
        }
        Integer needUpdate = 10041002;
        try {
            needUpdate = userMapper.findNeedUpdate(loginInfoDto.getUserId(),Integer.parseInt(systemparampos.get(0).get("paramValue")) );
        } catch (Exception e) {
            logger.error("数据库可能缺少字段",e);
        }
        return needUpdate;
    }

    //初始化
    @Override
    public void insertInitParam(String companyId)
    {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        systemParamMapper.insertInitParam(loginInfoDto.getAppId(),companyId,loginInfoDto.getUserId().toString(),loginInfoDto.getCompanyId().toString());
    }
}
